package api

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"web_api_gogf/app/model"
	"web_api_gogf/app/service"
	"web_api_gogf/library/response"
)

var Login = LoginApi{}

type LoginApi struct {
}

//账号登录
func (a *LoginApi) Account(r *ghttp.Request) {
	var (
		apiReq     *model.SysUsersApiSignReq
		serviceReq *model.SysUsersServiceSiginReq
		sysUser    *model.SysUsers
		token      interface{}
	)
	if err := r.ParseForm(&apiReq); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	if err := gconv.Struct(apiReq, &serviceReq); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	//调用登录方法并获取用户数据
	sysUser, err := service.SysUser.Login(serviceReq)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	token, err = service.SysUser.TokenCreate(sysUser, nil)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.Json(r, 0, "获取成功", g.Map{
		"token":    token,
		"userData": sysUser,
	})
}

//退出登录接口
func (a *LoginApi) Logout(r *ghttp.Request) {
	//过滤分析用户token值
	authorization := r.Header.Get("Authorization")
	authorizationArr := gstr.Explode(" ", authorization)
	userToken := authorizationArr[1]
	userData, err := service.SysUser.TokenGetData(userToken)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	if userData == nil {
		response.JsonExit(r, 1, "用户不存在")
	}
	if _, err := service.SysUser.TokenDelete(userToken); err != nil {
		response.Json(r, 1, "注销失败")
	}
	response.Json(r, 0, "注销成功")
}
